package com.homework.controller;

import com.homework.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;

@Slf4j
@RestController
@RequestMapping("/api/debug")
public class DatabaseTestController {

    @Autowired
    private DataSource dataSource;

    /**
     * 测试数据库连接
     */
    @GetMapping("/db-connection")
    public Result<String> testDatabaseConnection() {
        try {
            log.info("开始测试数据库连接");
            Connection connection = dataSource.getConnection();

            if (connection != null && !connection.isClosed()) {
                DatabaseMetaData metaData = connection.getMetaData();
                String info = String.format("数据库连接成功 - 数据库: %s, 版本: %s, URL: %s, 用户: %s",
                        metaData.getDatabaseProductName(),
                        metaData.getDatabaseProductVersion(),
                        metaData.getURL(),
                        metaData.getUserName());

                log.info(info);
                connection.close();
                return Result.success(info);
            } else {
                String error = "数据库连接失败 - 连接为null或已关闭";
                log.error(error);
                return Result.error(error);
            }

        } catch (Exception e) {
            String error = "数据库连接测试失败: " + e.getMessage();
            log.error(error, e);
            return Result.error(error);
        }
    }

    /**
     * 检查admin表是否存在
     */
    @GetMapping("/check-admin-table")
    public Result<String> checkAdminTable() {
        try {
            log.info("检查admin表是否存在");
            Connection connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();

            ResultSet tables = metaData.getTables(null, null, "admin", null);
            boolean tableExists = tables.next();
            tables.close();

            if (!tableExists) {
                String error = "admin表不存在";
                log.error(error);
                connection.close();
                return Result.error(error);
            }

            // 检查表结构
            ResultSet columns = metaData.getColumns(null, null, "admin", null);
            StringBuilder tableInfo = new StringBuilder("admin表结构:\n");

            while (columns.next()) {
                tableInfo.append(String.format("  列: %s, 类型: %s, 可空: %s\n",
                        columns.getString("COLUMN_NAME"),
                        columns.getString("TYPE_NAME"),
                        columns.getString("IS_NULLABLE")));
            }
            columns.close();
            connection.close();

            log.info("admin表检查完成");
            return Result.success(tableInfo.toString());

        } catch (Exception e) {
            String error = "检查admin表失败: " + e.getMessage();
            log.error(error, e);
            return Result.error(error);
        }
    }

    /**
     * 检查数据库中的数据
     */
    @GetMapping("/check-admin-data")
    public Result<String> checkAdminData() {
        try {
            log.info("检查admin表中的数据");
            Connection connection = dataSource.getConnection();

            ResultSet rs = connection.createStatement().executeQuery(
                "SELECT id, username, created_at, updated_at FROM admin LIMIT 10");

            StringBuilder dataInfo = new StringBuilder("admin表数据:\n");
            int count = 0;

            while (rs.next()) {
                count++;
                dataInfo.append(String.format("  ID: %d, 用户名: %s, 创建时间: %s, 更新时间: %s\n",
                        rs.getLong("id"),
                        rs.getString("username"),
                        rs.getTimestamp("created_at"),
                        rs.getTimestamp("updated_at")));
            }

            rs.close();
            connection.close();

            if (count == 0) {
                dataInfo.append("  没有找到任何数据\n");
                log.warn("admin表中没有数据");
            } else {
                log.info("admin表中找到{}条数据", count);
            }

            return Result.success(dataInfo.toString());

        } catch (Exception e) {
            String error = "检查admin数据失败: " + e.getMessage();
            log.error(error, e);
            return Result.error(error);
        }
    }
}